package com.lcq.gulimall.ssoserver.controller;

import com.lcq.gulimall.ssoserver.vo.LoginVo;
import com.sun.deploy.net.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {
    @Autowired
    StringRedisTemplate redisTemplate;
    @RequestMapping("doLogin")
    public String doLogin(LoginVo loginVo, HttpServletResponse response){
        if (loginVo!=null){
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            redisTemplate.opsForValue().set(uuid,loginVo.getName());
            Cookie cookie = new Cookie("sso_token",uuid);
            response.addCookie(cookie);
            return "redirect:"+loginVo.getRedirect_url()+"?token="+uuid;
        }
        return "redirect:localhost:8080/login.html";
    }

    @ResponseBody
    @RequestMapping("getLoginInfo")
    public String getLoginInfo(String token){
        String name = redisTemplate.opsForValue().get(token);
        return name;
    }

    @RequestMapping("login.html")
    public String login(@RequestParam("redirect_url") String redirect_url,
                        @CookieValue(value = "sso_token",required = false) String token){
        if (!StringUtils.isEmptyOrWhitespace(token)){
            return "redirect:"+redirect_url+"?token="+token;
        }
        return "login";
    }
}
